package com.wise.site.model;

import java.io.InputStream;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;

import com.baidu.mapapi.BMapManager;
import com.baidu.mapapi.GeoPoint;
import com.baidu.mapapi.MKAddrInfo;
import com.baidu.mapapi.MKBusLineResult;
import com.baidu.mapapi.MKDrivingRouteResult;
import com.baidu.mapapi.MKGeneralListener;
import com.baidu.mapapi.MKLocationManager;
import com.baidu.mapapi.MKPoiResult;
import com.baidu.mapapi.MKSearch;
import com.baidu.mapapi.MKSearchListener;
import com.baidu.mapapi.MKSuggestionResult;
import com.baidu.mapapi.MKTransitRouteResult;
import com.baidu.mapapi.MKWalkingRouteResult;
import com.baidu.mapapi.MapController;
import com.baidu.mapapi.MapView;
import com.baidu.mapapi.Overlay;
import com.wise.site.R;
import com.wise.site.WiseSiteApplication;
import com.wise.site.utils.Constanct;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.drawable.BitmapDrawable;
import android.location.Location;
import com.baidu.mapapi.LocationListener;

import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
import android.widget.Toast;

public class MapActivity extends com.baidu.mapapi.MapActivity {
	private BMapManager mBMapMan;
	private BitmapDrawable overly;
	private ProgressDialog mProgressDialog;
	private GeoPoint startPoint;
	private GeoPoint destPoint;
	private String area;
	private LocationListener listener;
	private MapView mMapView;
	private MKGeneralListener mGeneralListener = new MKGeneralListener() {
		@Override
		public void onGetNetworkState(int arg0) {

		}

		@Override
		public void onGetPermissionState(int arg0) {

		}
	};

	protected void showProgress() {
		if (mProgressDialog == null) {
			mProgressDialog = ProgressDialog.show(this, null,
					getString(R.string.loading));
		} else if (!mProgressDialog.isShowing()) {
			mProgressDialog.show();
		}
		new Handler().postDelayed(new Runnable() {

			@Override
			public void run() {
				try {
					mProgressDialog.dismiss();
				} catch (Exception e) {
				}
			}
		}, 10000);
	}

	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);

		Intent intent = getIntent();
		final String title = intent.getStringExtra(Constanct.INTENT_TITLE);
		// double lat = intent.getDoubleExtra(Constanct.INTENT_LAT, -1);
		// double lon = intent.getDoubleExtra(Constanct.INTENT_LON, -1);
		final String addr = intent.getStringExtra(Constanct.INTENT_ADDR);
		overly = (BitmapDrawable) getResources().getDrawable(
				R.drawable.dest_mark);

		setContentView(R.layout.map_layout);
		mBMapMan = WiseSiteApplication.getContext().getBMapMan();
		
		super.initMapActivity(mBMapMan);
		mMapView = (MapView) findViewById(R.id.bmapsView);

		WiseSiteApplication.getContext().mHandler.post(new Runnable() {
			@Override
			public void run() {
				showProgress();
				listener = new LocationListener() {

					@Override
					public void onLocationChanged(Location lastLoc) {
						// 不需要时移除监听
						mBMapMan.getLocationManager().removeUpdates(listener);
						/*MKSearchListener mMyAddrListener = new MKSearchListener() {

							@Override
							public void onGetWalkingRouteResult(
									MKWalkingRouteResult arg0, int arg1) {
								// TODO Auto-generated method stub

							}

							@Override
							public void onGetTransitRouteResult(
									MKTransitRouteResult arg0, int arg1) {
								// TODO Auto-generated method stub

							}

							@Override
							public void onGetSuggestionResult(
									MKSuggestionResult arg0, int arg1) {
								// TODO Auto-generated method stub

							}

							@Override
							public void onGetPoiResult(MKPoiResult res,
									int arg1, int arg2) {
							}

							@Override
							public void onGetDrivingRouteResult(
									MKDrivingRouteResult arg0, int arg1) {
								// TODO Auto-generated method stub

							}

							public void onGetBusDetailResult(
									MKBusLineResult arg0, int arg1) {
							}

							@Override
							public void onGetAddrResult(MKAddrInfo arg0,
									int arg1) {
								if (arg0 != null
										&& arg0.addressComponents != null && area == null) {
									area = arg0.addressComponents.city;
									return;
								}
								
								if (arg0 != null
										&& arg0.geoPt != null) {
									MapController mMapController = mMapView
											.getController(); // 得到mMapView的控制权,可以用它控制和驱动平移和缩放
									destPoint = arg0.geoPt;
									mMapController.setCenter(destPoint); // 设置地图中心点
									mMapController.setZoom(13); // 设置地图zoom级别

									MarkOverlay mark = new MarkOverlay(title,
											destPoint);
									mMapView.getOverlays().add(mark);
								}
								mProgressDialog.dismiss();
							}
						};*/
						startPoint = new GeoPoint((int) (1000000.0D * lastLoc
								.getLatitude()), (int) (1000000.0D * lastLoc
								.getLongitude()));
						MarkOverlay mark = new MarkOverlay(title,
								startPoint);
						mMapView.getOverlays().add(mark);
						
						MapController mMapController = mMapView
						.getController(); // 得到mMapView的控制权,可以用它控制和驱动平移和缩放
						
						JSONObject jsonObject = getLocationInfo(addr);
						//JSONObject jsonObject = getLocationInfo("深圳上梅林");
						double dest[] = getLatLon(jsonObject);
						if(dest[0] == 0 && dest[1] == 0){
							
						}else{
							destPoint = new GeoPoint((int)(1000000.0D * dest[0]), (int)(1000000.0D * dest[1]));
						}
						
						if(destPoint == null){
							mMapController.setCenter(startPoint);
							mMapController.setZoom(13);
							return;
						}
						int minLat = Math.min(startPoint.getLatitudeE6(), destPoint.getLatitudeE6());
						int minLon = Math.min(startPoint.getLongitudeE6(), destPoint.getLongitudeE6());
						int lat = Math.abs(startPoint.getLatitudeE6() - destPoint.getLatitudeE6());
						int lon = Math.abs(startPoint.getLongitudeE6() - destPoint.getLongitudeE6());
						mMapController.setCenter(new GeoPoint(lat/2 + minLat, lon/2 + minLon));
						//mMapController.setCenter(startPoint); // 设置地图中心点
						//mMapController.setZoom(13); // 设置地图zoom级别
						mMapController.zoomToSpan(lat, lon);
						
						MarkOverlay markd = new MarkOverlay(title,
								destPoint);
						mMapView.getOverlays().add(markd);
//						MKSearch mKMySearch = new MKSearch();
//						mKMySearch.init(mBMapMan, mMyAddrListener);
//						mKMySearch.geocode(addr, null);
//						mKMySearch.reverseGeocode(startPoint);
					}

				};
				// 注册监听
				mBMapMan.getLocationManager().requestLocationUpdates(listener);

			}
		});
		
		// mBMapMan.getLocationManager().enableProvider(MKLocationManager.MK_GPS_PROVIDER);
		// mBMapMan.getLocationManager().enableProvider(MKLocationManager.MK_NETWORK_PROVIDER);
		// mBMapMan.getLocationManager().setNotifyInternal(600, 10);

		mMapView.setBuiltInZoomControls(true); // 设置启用内置的缩放控件

		((TextView) findViewById(R.id.activity_title))
				.setText(R.string.location_title);
		findViewById(R.id.search_input).setOnClickListener(
				new OnClickListener() {

					@Override
					public void onClick(View arg0) {
						if (startPoint == null) {
							Toast.makeText(MapActivity.this, "缺少起点或终点", Toast.LENGTH_SHORT);
							return;
						} else if(destPoint == null){
							destPoint = startPoint;
						}
						SearchLine param = new SearchLine();
						param.startCity = area;
						param.startY = startPoint.getLatitudeE6();
						param.startX = startPoint.getLongitudeE6();
						param.endY = destPoint.getLatitudeE6();
						param.endX = destPoint.getLongitudeE6();
						SearchLineActivity.startActivity(MapActivity.this,
								param);
					}
				});

		findViewById(R.id.title_back).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		findViewById(R.id.search_path).setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				/*Intent intent = new Intent(android.content.Intent.ACTION_VIEW, Uri.parse("http://ditu.google.cn/maps?hl=zh&mrt=loc&q=" + startPoint.getLatitudeE6()/1000000.0D + "," + startPoint.getLongitudeE6()/1000000.0D));
				intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK & Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
				intent.setClassName("com.google.android.apps.maps", "com.google.android.maps.MapsActivity");
				
				startActivity(intent);*/
				
				
				if(destPoint == null){
					Toast.makeText(MapActivity.this, "缺少起点或终点", Toast.LENGTH_SHORT).show();
					return;
				}
				
				
				Resources resources = getResources();
				final CharSequence[] items = {resources.getString(R.string.bus), resources.getString(R.string.walk), resources.getString(R.string.driving)}; 
                AlertDialog.Builder builder = new AlertDialog.Builder(MapActivity.this);
                builder.setTitle(R.string.select_access); 
                builder.setItems(items, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int item) { 
                        StringBuilder params = new StringBuilder().append("&dirflg="); 
                        switch (item) {
                        case 0: 
                            params.append("r"); 
                            break; 
                        case 1: 
                            params.append("w"); 
                            break; 
                        case 2: 
                            params.append("d"); 
                            break; 
                        default: 
                            break; 
                        }
                        getMap(params.toString());
                    } 
                }); 

                AlertDialog alert = builder.create(); 
                alert.show();

				
				// TODO Auto-generated method stub
				/*MKSearch mKMySearch = new MKSearch();
				MKPlanNode start = new MKPlanNode();
				start.pt = new GeoPoint((int) (40.003834809598516 * 1E6), (int) (116.3263213634491 * 1E6));
				mMapView.getController().setCenter(start.pt);
				MKPlanNode end = new MKPlanNode();
				end.pt = new GeoPoint((int)(39.99142 * 1E6),(int)(116.39026999999998* 1E6)); 
				mKMySearch.init(mBMapMan, mMyAddrListener);
				mKMySearch.setDrivingPolicy(MKSearch.ECAR_TIME_FIRST);
				mKMySearch.drivingSearch("北京", start, "北京", end);*/
			}
		});
	}
	
	private void getMap(String params) {
		String path = "http://ditu.google.cn/maps?f=d&source=s_d&saddr=" 
				+ startPoint.getLatitudeE6()/1000000.0D + "," + startPoint.getLongitudeE6()/1000000.0D
				+ "&daddr=" + destPoint.getLatitudeE6()/1000000.0D + "," + destPoint.getLongitudeE6()/1000000.0D
				+ "&hl=zh&t=m&" + params;
		try {
			Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(path)); 
	        i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK & Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS); 
	        i.setClassName("com.google.android.apps.maps", "com.google.android.maps.MapsActivity"); 
	        startActivity(i);
		} catch (Exception e) {
			if(destPoint == null || startPoint == null){
				Toast.makeText(MapActivity.this, "缺少起点或终点", Toast.LENGTH_SHORT).show();
			}else{
				Toast.makeText(this, R.string.not_install_google_map, Toast.LENGTH_SHORT).show();
				Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(path));
				startActivity(i);
			}
		}
	}
	
	

	@Override
	protected void onPause() {
		if (mBMapMan != null) {
			mBMapMan.stop();
		}
		super.onPause();
	}

	@Override
	protected void onResume() {
		if (mBMapMan != null) {
			mBMapMan.start();
		}
		super.onResume();
	}

	@Override
	protected boolean isRouteDisplayed() {
		// TODO Auto-generated method stub
		return false;
	}

	public class MarkOverlay extends Overlay {
		private GeoPoint geoPoint;
		private String title;
		private Paint paint = new Paint();

		public MarkOverlay(String title, GeoPoint geoPoint) {
			this.geoPoint = geoPoint;
			this.title = title;
		}

		@Override
		public void draw(Canvas canvas, MapView mapView, boolean shadow) {
			// 在天安门的位置绘制一个String
			Point point = mapView.getProjection().toPixels(geoPoint, null);
			canvas.drawBitmap(overly.getBitmap(),
					point.x - overly.getIntrinsicWidth() / 2,
					point.y - overly.getIntrinsicHeight(), null);
			// canvas.drawText(title, point.x, point.y -
			// overly.getIntrinsicHeight(), paint);
		}
	}
	
	private JSONObject getLocationInfo(String addr){
		StringBuilder sb = new StringBuilder();
		JSONObject jsonObject = null;// = new JSONObject();
		addr = addr.replaceAll(" ", "%20");
		try {
			HttpPost httppost = new HttpPost("http://maps.google.com/maps/api/geocode/json?address=" + addr + "&sensor=false");
			HttpClient client = new DefaultHttpClient();
			HttpResponse response = client.execute(httppost);
			HttpEntity entity = response.getEntity();
			InputStream stream = entity.getContent();
			int b;
			while ((b = stream.read()) != -1) {
				sb.append((char) b);
			}
			jsonObject = new JSONObject(sb.toString());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return jsonObject;
	}
	
	private double[] getLatLon(JSONObject jsonObject){
		double latLon[] = new double[2];
		try {
			latLon [0] = ((JSONArray)jsonObject.get("results")).getJSONObject(0).getJSONObject("geometry").getJSONObject("location").getDouble("lat");
			latLon [1] = ((JSONArray)jsonObject.get("results")).getJSONObject(0).getJSONObject("geometry").getJSONObject("location").getDouble("lng");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return latLon;
	}

}
